<template>
  <view class="chat-container">
    <!-- 消息列表 -->
    <scroll-view
        class="chat-messages"
        :scroll-into-view="lastMessageId"
        scroll-y
    >
      <view v-for="(msg, index) in messages" :key="msg.id" :id="msg.id">
        <ChatMessage :message="msg" :isUser="msg.sender === 'user'" />
      </view>
    </scroll-view>

    <!-- 输入框 -->
    <view class="chat-input-container">
      <input
          class="chat-input"
          placeholder="请输入消息..."
          v-model="inputMessage"
          @confirm="sendMessage"
      />
      <button class="send-button" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script>
import ChatMessage from './ChatMessage.vue';

export default {
  name: 'ChatPage',
  components: { ChatMessage },
  data() {
    return {
      messages: [
        { id: '1', sender: 'bot', content: '你好！有什么可以帮你的吗？' },
        { id: '2', sender: 'user', content: '你好，我想了解一下产品。' },
      ],
      inputMessage: '',
    };
  },
  computed: {
    lastMessageId() {
      return this.messages.length > 0
          ? this.messages[this.messages.length - 1].id
          : '';
    },
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage.trim()) return;

      // 用户发送消息
      this.messages.push({
        id: `${Date.now()}`,
        sender: 'user',
        content: this.inputMessage,
      });

      this.inputMessage = '';

      // 模拟对方回复
      setTimeout(() => {
        this.messages.push({
          id: `${Date.now() + 1}`,
          sender: 'bot',
          content: '好的，我正在为您处理。',
        });
      }, 1000);
    },
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  background-color: #f5f5f5;
  padding: 10px;
}

.chat-input-container {
  display: flex;
  padding: 10px;
  background-color: #ffffff;
}

.chat-input {
  flex: 1;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 0 10px;
}

.send-button {
  margin-left: 10px;
  height: 40px;
  padding: 0 20px;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 5px;
  font-size: 16px;
}
</style>
